import React, { useState, useEffect } from 'react';
import { Card } from './ui/card';
import { Switch } from './ui/switch';
import { Slider } from './ui/slider';
import { Label } from './ui/label';
import { Volume2, VolumeX, MessageSquare } from 'lucide-react';

interface DetectionResult {
  detected: boolean;
  confidence?: number;
  direction?: string;
  distance?: string;
  boundingBox?: {
    x: number;
    y: number;
    width: number;
    height: number;
  };
  message?: string;
}

interface VoiceFeedbackProps {
  result: DetectionResult;
  targetObject: string;
}

const VoiceFeedback: React.FC<VoiceFeedbackProps> = ({ result, targetObject }) => {
  const [voiceEnabled, setVoiceEnabled] = useState<boolean>(true);
  const [volume, setVolume] = useState<number>(80);
  const [lastMessage, setLastMessage] = useState<string>('');

  // 生成语音消息
  useEffect(() => {
    if (!voiceEnabled) return;

    // 使用后端提供的消息或生成默认消息
    let message = result.message || '';
    if (!message) {
      if (result.detected) {
        message = `已检测到${targetObject}，位于${result.direction || '未知方位'}，距离${
          result.distance === 'near' ? '近' : 
          result.distance === 'medium' ? '中等' : '远'
        }`;
      } else {
        message = `未检测到${targetObject}，请尝试转换视角`;
      }
    }

    setLastMessage(message);

    // 使用Web Speech API播放语音
    const speech = new SpeechSynthesisUtterance(message);
    speech.lang = 'zh-CN';
    speech.volume = volume / 100;
    window.speechSynthesis.speak(speech);
  }, [result, targetObject, voiceEnabled, volume]);

  // 处理音量变化
  const handleVolumeChange = (value: number[]) => {
    setVolume(value[0]);
  };

  // 处理语音开关变化
  const handleVoiceToggle = (checked: boolean) => {
    setVoiceEnabled(checked);
    if (!checked) {
      window.speechSynthesis.cancel(); // 停止当前语音
    }
  };

  // 重新播放最后的消息
  const handleReplay = () => {
    if (!voiceEnabled || !lastMessage) return;
    
    const speech = new SpeechSynthesisUtterance(lastMessage);
    speech.lang = 'zh-CN';
    speech.volume = volume / 100;
    window.speechSynthesis.speak(speech);
  };

  return (
    <Card className="p-4">
      <div className="flex items-center justify-between mb-4">
        <div className="flex items-center">
          <MessageSquare className="h-5 w-5 text-primary mr-2" />
          <h3 className="font-medium">语音反馈</h3>
        </div>
        <div className="flex items-center">
          <Label htmlFor="voice-toggle" className="mr-2">启用语音</Label>
          <Switch 
            id="voice-toggle" 
            checked={voiceEnabled} 
            onCheckedChange={handleVoiceToggle} 
          />
        </div>
      </div>

      <div className="space-y-4">
        <div className="flex items-center">
          <div className="mr-4">
            {voiceEnabled ? (
              <Volume2 
                className="h-5 w-5 text-primary cursor-pointer" 
                onClick={handleReplay}
                title="点击重新播放"
              />
            ) : (
              <VolumeX className="h-5 w-5 text-gray-400" />
            )}
          </div>
          <div className="flex-1">
            <Slider
              disabled={!voiceEnabled}
              value={[volume]}
              min={0}
              max={100}
              step={1}
              onValueChange={handleVolumeChange}
              className={voiceEnabled ? "" : "opacity-50"}
            />
          </div>
          <div className="ml-4 w-8 text-center">
            <span className="text-sm">{volume}%</span>
          </div>
        </div>

        <div className="p-3 bg-gray-50 rounded-md">
          <p className="text-sm text-gray-700">
            <span className="font-medium">最近语音提示：</span> {lastMessage || '无'}
          </p>
        </div>

        <div className="text-xs text-gray-500">
          <p>语音提示将告知您目标物体的位置信息，帮助您更快找到目标。点击音量图标可重新播放提示。</p>
        </div>
      </div>
    </Card>
  );
};

export default VoiceFeedback;